package com.weishao.dbmapper;

import java.util.Objects;
import javax.sql.DataSource;
import com.weishao.dbmapper.pojo.TaskMapTypeEnum;
import com.weishao.dbmapper.pojo.TaskParamEntity;

/**
 * 映射引擎抽象基类
 * 
 * @author tang
 *
 */
public abstract class AbstractMapperEngine implements IDatabaseMapperEngine {

	protected boolean quiteWhenCoderMapperException;

	protected DataSource dataSource;

	public AbstractMapperEngine() {
		this.quiteWhenCoderMapperException = true;
	}

	@Override
	public boolean isQuietWhenCoderMapperException() {
		return this.quiteWhenCoderMapperException;
	}

	@Override
	public void setQuietWhenCoderMapperException(boolean quiet) {
		this.quiteWhenCoderMapperException = quiet;
	}

	@Override
	public void setMapperEngineDataSource(DataSource sourceDataSource) {
		this.dataSource = Objects.requireNonNull(sourceDataSource, "来源端的数据源示例DataSource为null");
	}

	@Override
	public void runMapperTransfer(TaskParamEntity task, IResultRowHandler handler) {
		if (TaskMapTypeEnum.MultiByOne == task.getMapType()) {
			if (Objects.isNull(task.getViewSql()) || task.getViewSql().trim().isEmpty()) {
				throw new IllegalArgumentException("任务参数配置为多对一映射，但关联查询的SQL语句为空");
			}
		}

		if (Objects.isNull(dataSource)) {
			throw new RuntimeException("请先调用setMapperEngineDataSource()设置数据查询的数据源");
		}

		if (Objects.isNull(task.getFieldsMapper()) || task.getFieldsMapper().isEmpty()) {
			throw new IllegalArgumentException("配置错误，字段映射关系为空");
		}

		if (Objects.isNull(task.getValuesMapper())) {
			throw new IllegalArgumentException("代码映射关系为null");
		}

		if (task.getFetchSize() < 100) {
			throw new IllegalArgumentException("参数fetchSize的值不得小于100");
		}

		this.handleTransfer(task, handler);
	}

	/**
	 * 转换处理
	 * 
	 * @param task    任务参数实例
	 * @param handler 结果处理器
	 */
	protected abstract void handleTransfer(TaskParamEntity task, IResultRowHandler handler);
}
